<?php

namespace app\admin\controller\air;

use app\common\controller\Backend;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\response\Json;
use app\admin\model\Area;

/**
 * 特惠包机列管理
 *
 * @icon fa fa-circle-o
 */
class Charter extends Backend
{

    /**
     * Charter模型对象
     * @var \app\admin\model\air\Charter
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\air\Charter;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("unitList", $this->model->getUnitList());
        $this->view->assign("citysList", $this->model->getCitysList());
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $this->view->assign('start_city_type', 'in');
            $this->view->assign('end_city_type', 'in');
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $startCityType = trim($params['starttype']);
        $endCityType = trim($params['endtype']);
        
        $startCity = $this->request->post('start_city', 0);
        $startCityO = $this->request->post('start_city_o', 0);
        if ($startCityType == 'in' && empty($startCity)) {
            $this->error(__('起飞城市不能为空'));
        }
        if ($startCityType == 'out' && empty($startCityO)) {
            $this->error(__('起飞城市不能为空'));
        }

        $endCity = $this->request->post('end_city', 0);
        $endCityO = $this->request->post('end_city_o', 0);
        if ($endCityType == 'in' && empty($endCity)) {
            $this->error(__('降落城市不能为空'));
        }
        if ($endCityType == 'out' && empty($endCityO)) {
            $this->error(__('降落城市不能为空'));
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['start_area_id'] = $startCityType == 'in' ? $startCity : $startCityO;
            $params['end_area_id'] = $endCityType == 'in' ? $endCity : $endCityO;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $startProvince = '';
            $startProvinceName = '';
            $startCity = '';
            $startCityName = '';
            $endProvince = '';
            $endProvinceName = '';
            $endCity = '';
            $endCityName = '';

            $startIslandO = '';
            $startIslandOName = '';
            $startCountryO = '';
            $startCountryOName = '';
            $startCityO = '';
            $startCityOName = '';

            $endIslandO = '';
            $endIslandOName = '';
            $endCountryO = '';
            $endCountryOName = '';
            $endCityO = '';
            $endCityOName = '';


            // 查找城市上级的身份
            $startArea = Area::get($row->start_area_id);
            $startPArea = Area::get($startArea->pid);
            if ($startArea->in_out == '1') {
                $startCityType = 'in';
                $startProvince = $startArea->pid;
                $startProvinceName = $startPArea->name;;
                $startCity = $startArea->id;
                $startCityName = $startArea->name;
            } else {
                $startCityType = 'out';

                $startPPArea = Area::get($startPArea->pid);
                $startIslandO = $startPPArea->id;
                $startIslandOName = $startPPArea->name;
                $startCountryO = $startPArea->id;
                $startCountryOName = $startPArea->name;
                $startCityO = $startArea->id;
                $startCityOName = $startArea->name;

            }

            $endArea = Area::get($row->end_area_id);
            $endPArea = Area::get($endArea->pid);
            if ($endArea->in_out == '1') {
                $endCityType = 'in';
                $endProvince = $endArea->pid;
                $endProvinceName = $endPArea->name;;
                $endCity = $endArea->id;
                $endCityName = $endArea->name;
            } else {
                $endCityType = 'out';

                $endPPArea = Area::get($endPArea->pid);
                $endIslandO = $endPPArea->id;
                $endIslandOName = $endPPArea->name;
                $endCountryO = $endPArea->id;
                $endCountryOName = $endPArea->name;
                $endCityO = $endArea->id;
                $endCityOName = $endArea->name;
            }

            $this->view->assign('start_city_type', $startCityType);
            $this->view->assign('end_city_type', $endCityType);
            
            // 国内/港澳台城市
            $this->view->assign('start_province', $startProvince);
            $this->view->assign('start_province_name', $startProvinceName);
            $this->view->assign('start_city', $startCity);
            $this->view->assign('start_city_name', $startCityName);

            $this->view->assign('end_province', $endProvince);
            $this->view->assign('end_province_name', $endProvinceName);
            $this->view->assign('end_city', $endCity);
            $this->view->assign('end_city_name', $endCityName);

            // 国际城市
            $this->view->assign('start_island_o', $startIslandO);
            $this->view->assign('start_island_o_name', $startIslandOName);
            $this->view->assign('start_country_o', $startCountryO);
            $this->view->assign('start_country_o_name', $startCountryOName);
            $this->view->assign('start_city_o', $startCityO);
            $this->view->assign('start_city_o_name', $startCityOName);

            $this->view->assign('end_island_o', $endIslandO);
            $this->view->assign('end_island_o_name', $endIslandOName);
            $this->view->assign('end_country_o', $endCountryO);
            $this->view->assign('end_country_o_name', $endCountryOName);
            $this->view->assign('end_city_o', $endCityO);
            $this->view->assign('end_city_o_name', $endCityOName);

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $startCityType = trim($params['starttype']);
        $endCityType = trim($params['endtype']);
        
        $startCity = $this->request->post('start_city', 0);
        $startCityO = $this->request->post('start_city_o', 0);
        if ($startCityType == 'in' && empty($startCity)) {
            $this->error(__('起飞城市不能为空'));
        }
        if ($startCityType == 'out' && empty($startCityO)) {
            $this->error(__('起飞城市不能为空'));
        }

        $endCity = $this->request->post('end_city', 0);
        $endCityO = $this->request->post('end_city_o', 0);
        if ($endCityType == 'in' && empty($endCity)) {
            $this->error(__('降落城市不能为空'));
        }
        if ($endCityType == 'out' && empty($endCityO)) {
            $this->error(__('降落城市不能为空'));
        }
        /*
        $startCity = $this->request->post('start_city', 0);
        $endCity = $this->request->post('end_city', 0);
        if (empty($startCity) || empty($endCity)) {
            $this->error(__('起飞或降落城市不能为空'));
        }
         */
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $params['start_area_id'] = $startCityType == 'in' ? $startCity : $startCityO;
            $params['end_area_id'] = $endCityType == 'in' ? $endCity : $endCityO;
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


}
